#include "trans_file.h"
#include "client.h"
#include "child_pthread.h"
//发送一个带有状态的小火车
void send_session(int new_fd,train_state_t* pt,int state,char* buf){
    bzero(pt,sizeof(train_state_t));
    pt->state=state;
    strcpy(pt->buf,buf);
    pt->data_len=4+strlen(pt->buf);
    send_n(new_fd,&pt->data_len,4);
    send_n(new_fd,&pt->state,pt->data_len);
}
//循环接收数据，直到接收到自己想要数量
int recv_n(int sfd,void* buf,int data_len){
    char *p=(char*)buf;
    int total=0,ret;
    while(total<data_len){
        ret=recv(sfd,p+total,data_len-total,0);
        if(0==ret){//代表对端断开了
            return -1;
        }
        total+=ret;
    }
    return 0;
}
//循环发送数据，直到发送到自己想要数量
int send_n(int sfd,void* buf,int data_len){
    char *p=(char*)buf;
    int total=0,ret;
    while(total<data_len){
        ret=send(sfd,p+total,data_len-total,0);
        total+=ret;
    }
    return 0;
}
//给服务器上传数据
int upload(int fd_up, char* file_name){
	
	int fd_file = open(file_name, O_RDONLY);
	if(fd_file == -1){
		return -1 ;
	}
	char *read_buf = (char*)malloc(8 * 1024);
	bzero(read_buf, 8 * 1024);
	int nread ;
	while(1){
		nread = read(fd_file, read_buf, 8192);
		if(nread < 8192){
			send(fd_up, &nread, sizeof(int), 0);
			send_n(fd_up, read_buf, nread);
			break ;
		}else{
			send(fd_up, &nread, sizeof(int), 0);
			send_n(fd_up, read_buf, nread);
		}
	}
	int flag = 0 ;
	send(fd_up, &flag, sizeof(flag), 0);
	close(fd_file);
	return 0 ;
}
//带有断点续传功能的下载
int download(int fd_down, char* file_name,train_off_t* pt){
	struct stat statbuf;
	int ret=stat(file_name,&statbuf);
	bzero(pt,sizeof(train_off_t));
	pt->state=OFF_T;
	if(ret==-1){
		pt->data_len=4+sizeof(off_t);
	}else{
		off_t file_off=statbuf.st_size;
		pt->file_off=file_off;
		pt->data_len=4+sizeof(off_t);
	}
	send_n(fd_down,&pt->data_len,4);
	send_n(fd_down,&pt->state,pt->data_len);

	int fd_file = open(file_name,O_RDWR|O_CREAT,0666);
	ERROR_CHECK(fd_file,-1,"open");
	lseek(fd_file,0,SEEK_END);
	char* write_buf = (char*)malloc(8192);
	bzero(write_buf, 8192);
	int nwrite ;
	while(1){
		recv_n(fd_down, &nwrite, sizeof(int));
		if(nwrite == 0){
			break ;
		}
		recv_n(fd_down, write_buf, nwrite);
		write(fd_file, write_buf, nwrite);
	}
	close(fd_file);
	return 0 ;
}
//把所输入指令多余空格去掉把并且最后的换行变成'\0'
void trim_space(char* src) {
	int index, cur ;
	for(cur = -1, index = 0 ; index < strlen(src); index ++){
		if(src[index] !=' ' && src[index] != '\n'){
			src[++cur] = src[index];
		}else {
			if(cur != -1 && src[cur] != ' '){
				src[++cur] = ' ';
			}
		}
	}
	src[cur]='\0';
}
//使用一个普通小火车给
void recv_result_from_server(int sfd,int* precv_len,char* buf){
    system("clear");
    bzero(precv_len,4);
    bzero(buf,100);
    recv_n(sfd, precv_len, 4);//接cd之后的路径,用普通火车
    recv_n(sfd, buf, *precv_len );
    printf("%s\n", buf);
}